package GPA;

import java.io.FileWriter;
import java.io.IOException;

public class Tes {
    public static void main(String[] args) {
        // 创建学生
        Student student = new Student("S001", "张三", "计科2001班");

        // 创建课程
        Course math = new Course("C001", "高等数学", 4.0);
        Course english = new Course("C002", "大学英语", 3.0);
        Course java = new Course("C003", "Java程序设计", 3.5);

        // 用于存储输出内容
        StringBuilder output = new StringBuilder();

        try {
            // 创建成绩（关联学生和课程）
            Score mathScore = new Score(student, math, 90);
            Score englishScore = new Score(student, english, 92);
            Score javaScore = new Score(student, java, 80);

            // 将成绩添加到学生的成绩列表中
            student.addScore(mathScore);
            student.addScore(englishScore);
            student.addScore(javaScore);

            // 收集所有课程成绩信息
            output.append(student.getName()).append("的所有课程成绩如下：\n");
            for (Score score : student.getScores()) {
                Course course = score.getCourse();
                String courseInfo = course.getCourseName() + "：" + score.getScore() + "分（学分：" + course.getCredit() + "）\n";
                output.append(courseInfo);
                System.out.print(courseInfo); // 控制台也输出
            }

            // 计算并收集GPA信息
            double gpa = student.calculateGPA();
            String gpaInfo = "\n" + student.getName() + "的最终GPA：" + String.format("%.2f", gpa) + "\n";
            output.append(gpaInfo);
            System.out.print(gpaInfo); // 控制台也输出

            // 保存到指定路径（C:\Users\fjzda\eclipse-workspace\output.txt）
            String filePath = "C:\\Users\\fjzda\\eclipse-workspace\\output.txt";
            try (FileWriter writer = new FileWriter(filePath)) {
                writer.write(output.toString());
                System.out.println("结果已保存到：" + filePath);
            } catch (IOException e) {
                System.out.println("文件写入失败：" + e.getMessage());
            }

        } catch (ScoreRangeException e) {
            String errorInfo = "成绩异常：" + e.getMessage() + "\n";
            System.out.print(errorInfo);
            // 异常信息也写入指定路径
            try (FileWriter writer = new FileWriter("C:\\Users\\fjzda\\eclipse-workspace\\output.txt")) {
                writer.write(errorInfo);
            } catch (IOException ex) {
                System.out.println("文件写入失败：" + ex.getMessage());
            }
        }
    }
}
